package com.vitabuybuy.tv.ui.mine

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.FragmentMineBinding
import com.vitabuybuy.tv.dto.BannerDto
import com.library.common.base.BaseFragment
import com.library.common.base.MessageModel
import com.library.common.base.appContext
import com.library.common.ext.logE
import com.library.common.ext.mmkv
import com.library.common.ext.setOnclickNoRepeat
import com.library.common.net.HeadInterceptor
import com.library.common.toast.XToast
import com.vitabuybuy.tv.ui.auth.BindEmailActivity
import com.vitabuybuy.tv.ui.auth.LoginActivity
import com.vitabuybuy.tv.ui.mine.address.AddressActivity
import com.vitabuybuy.tv.ui.mine.order.OrderListActivity
import com.vitabuybuy.tv.ui.mine.setting.SettingActivity
import com.vitabuybuy.tv.ui.mine.viewmodel.MineViewModel
import com.vitabuybuy.tv.ui.mine.wallet.MyWalletActivity
import com.library.common.util.MMKVContancts
import com.tencent.imsdk.TIMCallBack
import com.tencent.imsdk.TIMFriendshipManager
import com.tencent.imsdk.TIMUserProfile
import com.vitabuybuy.tv.BuildConfig

import com.vitabuybuy.tv.adaptebinding.ImageAdapter
import com.vitabuybuy.tv.adaptebinding.ImageAdapter.setCircleImageUrl
import com.vitabuybuy.tv.ui.MainActivity
import com.vitabuybuy.tv.ui.auth.VerifyEmailActivity
import com.vitabuybuy.tv.ui.mine.account.AccountManageActivity
import com.vitabuybuy.tv.ui.mine.bidding.MyBiddingActivity
import com.vitabuybuy.tv.ui.mine.coin.MyRewardCoinActivity
import com.vitabuybuy.tv.ui.mine.collect.CollectionActivity
import com.vitabuybuy.tv.ui.mine.comment.MyCommentActivity
import com.vitabuybuy.tv.ui.mine.coupons.MyCouponsActivity
import com.vitabuybuy.tv.ui.mine.dredge.OpenShopRuleActivity
import com.vitabuybuy.tv.ui.mine.follow.MyFollowActivity
import com.vitabuybuy.tv.ui.mine.foot.FootprintActivity
import com.vitabuybuy.tv.ui.mine.group.MyGroupBuyActivity
import com.vitabuybuy.tv.ui.mine.order.OrderCommissionActivity
import com.vitabuybuy.tv.ui.mine.order.after.AfterSaleActivity
import com.vitabuybuy.tv.ui.mine.talent.ApplyExpertActivity
import com.vitabuybuy.tv.ui.mine.talent.ExpertInfoActivity
import com.vitabuybuy.tv.ui.mine.talent.ExpertZoneActivity
import com.vitabuybuy.tv.ui.tencent.liveroom.IMLVBLiveRoomListener
import com.vitabuybuy.tv.ui.tencent.liveroom.MLVBLiveRoom
import com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.commondef.LoginInfo
import kotlinx.android.synthetic.main.fragment_mine.*
import java.util.HashMap

/**
 * 作者：SimGa
 * 日期：2020/11/29
 * 时间：10:49
 * 包名：com.vitabuybuy.tv.ui.cart
 */

class MineFragment : BaseFragment<MineViewModel, FragmentMineBinding>(){
    override val layoutId: Int
        get() = R.layout.fragment_mine


    override fun initView(savedInstanceState: Bundle?) {
//        initBanner()
        mBinding.viewModel = viewModel
        viewModel.isFirstLoading.set(true)
//        val images = resources.getStringArray(R.array.banner_list)
//        val bannerlist = ArrayList<BannerDto>()
//        for (image in images) {
//            bannerlist.add(BannerDto(image))
//        }
//        my_banner.setBannerData(bannerlist)
    }

    override fun lazyLoadData() {
        viewModel.applyTalentUserInfo.observe(this, Observer {
            mmkv.encode(MMKVContancts.EXECUTOR_ID, it.id)
            mmkv.encode(MMKVContancts.EXECUTOR_AVATAR, it.avatar)
            mmkv.encode(MMKVContancts.EXECUTOR_NICKNAME, it.realname)
            val loginInfo = LoginInfo().apply {
                sdkAppID = BuildConfig.LIVEAPPID.toLong()
                userID = "executor_".plus(it.id)
                userSig = it.userSign
                userName = it.realname
                userAvatar = it.avatar
            }
            MLVBLiveRoom.sharedInstance(appContext)
                .login(loginInfo, object : IMLVBLiveRoomListener.LoginCallback {
                    override fun onSuccess() {
                        ExpertZoneActivity.openActivity(mContext)
                    }

                    override fun onError(errCode: Int, errInfo: String?) {
                        errInfo?.run {
                            errCode.logE("JIA--errCode--")
                            this.logE("JIA--errInfo--")
                            XToast.error("直播登录失败，请联系管理员")
                        }
                    }
                })
        })
        viewModel.userInfoAndOrderCount.observe(this, Observer { it ->
            it.loginInfoDto.let {
                mmkv.encode(MMKVContancts.USER_AVATAR, it.avatar)
                mmkv.encode(MMKVContancts.USER_NICKNAME, it.nickname)
                mmkv.encode(MMKVContancts.USER_EMAIL, it.email)
                setCircleImageUrl(
                    ivAvatar,
                    it.avatar,
                    ContextCompat.getDrawable(mContext, R.drawable.wode_icon_touxiang)
                )
                tvName.text = it.nickname
                tvBindEmail.text =
                    if (it.email.isNullOrEmpty()) getString(R.string.bind_email_2) else it.email
                tvCollection.text = it.favoritesQuantity.toString()
                tvFollow.text = it.attentionQuantity.toString()
                tvFootprint.text = it.footprintQuantity.toString()
                tvCoupons.text = it.couponQuantity.toString()
            }
            it.orderCountDto.let {
                if (it.nonPaymentQuantity == 0) {
                    mBinding.tvWaitToPayUnread.visibility = View.GONE
                } else {
                    mBinding.tvWaitToPayUnread.visibility = View.VISIBLE
                    mBinding.tvWaitToPayUnread.text = it.nonPaymentQuantity.toString()
                }
                if (it.paidQuantity == 0) {
                    mBinding.tvWaitToDeliverUnread.visibility = View.GONE
                } else {
                    mBinding.tvWaitToDeliverUnread.visibility = View.VISIBLE
                    mBinding.tvWaitToDeliverUnread.text = it.paidQuantity.toString()
                }
                if (it.shippedQuantity == 0) {
                    mBinding.tvWaitToReceiveUnread.visibility = View.GONE
                } else {
                    mBinding.tvWaitToReceiveUnread.visibility = View.VISIBLE
                    mBinding.tvWaitToReceiveUnread.text = it.shippedQuantity.toString()
                }
                if (it.finishedQuantity == 0) {
                    mBinding.tvWaitToCommentUnread.visibility = View.GONE
                } else {
                    mBinding.tvWaitToCommentUnread.visibility = View.VISIBLE
                    mBinding.tvWaitToCommentUnread.text = it.finishedQuantity.toString()
                }
            }
        })
    }

    override fun eventHandling() {
        setOnclickNoRepeat(
            ivAvatar, llDeliverAddress, ivSetting, llCollection, llFollow,
            llFootprint, llCoupons, ivMyWallet, rlMyOrder,
            ivWaitToPay, ivWaitToDeliver, ivWaitToReceive, ivWaitToComment,
            ivAfterSale, tvBindEmail, ivOpenShop, ivAccountManagement,
            ivCommissionRecord, ivMyComment, ivMyBidding, ivMyGroupBuy,
            ivPayManage, rlExpertZone, rlSignIn, rlActivityReward
        ) { v ->
            if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                LoginActivity.openActivity(mContext)
                return@setOnclickNoRepeat
            }
            when (v) {
                ivAvatar -> PersonalInfoActivity.openActivity(mContext)
                ivSetting -> SettingActivity.openActivity(mContext)
                llCollection -> CollectionActivity.openActivity(mContext)
                llFollow -> MyFollowActivity.openActivity(mContext)
                llFootprint -> FootprintActivity.openActivity(mContext)
                llCoupons -> MyCouponsActivity.openActivity(mContext)
                ivMyWallet -> MyWalletActivity.openActivity(mContext)
                llDeliverAddress -> AddressActivity.openActivity(mContext, 10001)
                rlMyOrder -> OrderListActivity.openActivity(mContext, OrderListActivity.ALL)
                ivWaitToPay -> OrderListActivity.openActivity(
                    mContext,
                    OrderListActivity.WAITING_PAY
                )
                ivWaitToDeliver -> OrderListActivity.openActivity(
                    mContext,
                    OrderListActivity.WAITING_SEND
                )
                ivWaitToReceive -> OrderListActivity.openActivity(
                    mContext,
                    OrderListActivity.WAITING_RECEIVER
                )
                ivWaitToComment -> OrderListActivity.openActivity(
                    mContext,
                    OrderListActivity.WAITING_COMMENT
                )
//            ivAfterSale -> OrderListActivity.openActivity(mContext, OrderListActivity.AFTER_SALE)
                tvBindEmail -> if (viewModel.userInfoAndOrderCount.value?.loginInfoDto?.email.isNullOrEmpty()) {
                    BindEmailActivity.openActivity(
                        mContext,
                        bundleOf(Pair("from", BindEmailActivity.FROM_BIND_EMAIL))
                    )
                } else {
                    VerifyEmailActivity.openActivity(
                        mContext
                    )
                }
                ivOpenShop -> OpenShopRuleActivity.openActivity(mContext)
                ivAccountManagement -> AccountManageActivity.openActivity(mContext)
                ivCommissionRecord -> OrderCommissionActivity.openActivity(mContext)
                ivMyComment -> MyCommentActivity.openActivity(mContext)
                ivMyBidding -> MyBiddingActivity.openActivity(mContext)
                ivMyGroupBuy -> MyGroupBuyActivity.openActivity(mContext)
                ivPayManage -> MyRewardCoinActivity.openActivity(mContext)
                ivAfterSale -> AfterSaleActivity.openActivity(mContext)
                rlExpertZone -> {
                    when (viewModel.userInfoAndOrderCount.value?.loginInfoDto?.executorStatus) {
                        "未申请" -> ApplyExpertActivity.openActivity(mContext)
                        "通过" -> {
                            viewModel.userInfoAndOrderCount.value?.loginInfoDto?.run {
                                if (this.isExecutorEnable)
                                    viewModel.getTalentUserInfo()
                                else
                                    XToast.normal(getString(R.string.your_executor_disable_pls_call_service))
                            }
                        }
                        else -> ExpertInfoActivity.openActivity(mContext)
                    }
                }
                rlSignIn -> {
                    UserSignActivity.openActivity(mContext)
                }
                rlActivityReward -> {
                    ActivityRewardsActivity.openActivity(mContext)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
//        my_banner.startAutoPlay()
        if (mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
            viewModel.getUserInfoAndOrderCount()
        } else {
            ivAvatar.setImageResource(R.drawable.wode_icon_touxiang)
            tvName.text = getString(R.string.not_login)
            tvSignIn.text = getString(R.string.sign_in)
            tvBindEmail.text = getString(R.string.bind_email_2)
            tvCollection.text = "0"
            tvFollow.text = "0"
            tvFootprint.text = "0"
            tvCoupons.text = "0"
            mBinding.tvWaitToPayUnread.visibility = View.GONE
            mBinding.tvWaitToDeliverUnread.visibility = View.GONE
            mBinding.tvWaitToReceiveUnread.visibility = View.GONE
            mBinding.tvWaitToCommentUnread.visibility = View.GONE
        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            0 -> {
                viewModel.getUserInfoAndOrderCount()
            }
        }
    }

    override fun onPause() {
        super.onPause()
//        my_banner.stopAutoPlay()
    }

    private fun initBanner() {
        my_banner.loadImage { _, model, view, _ ->
            ImageAdapter.setNomalImageUrl(
                view as ImageView,
                (model as BannerDto.SlideListBean).image,
                ContextCompat.getDrawable(mContext, R.drawable.default_image)
            )
        }
    }
}